﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Data.SqlClient;
using HZ.MBSM.DBUtility;

public partial class Supervise_ReportShow : System.Web.UI.Page
{
    string strYear = "", strId="";
    protected void Page_Load(object sender, EventArgs e)
    {
        
        strId = SysFun.IsSQL(Request.QueryString["Goodsid"].ToString());
        string Type = SysFun.IsSQL(Request.QueryString["Type"].ToString());
        if (Type != "3")
        { 
          strYear = SysFun.IsSQL(Request.QueryString["Year"].ToString());  
        }
        string strArea = SysFun.IsSQL(Request.QueryString["Area"].ToString());        
        /**/
        /*自写编码*/
        int ImgWidth = 800; //1.[总宽度] ***图宽度 
        int ImgHeight = 440; //2.[总高度] ***图高度 
        int ItemNum = 1; //3.[项目数量] ***图表划分的块 
        int ChildNum = strArea.Split(',').Length; //4.[块数] ***大块中划分的子项的数量
        float ChildRate = 0.6f; //5.[各块总占空间比率]
        // int ChildSpace=15; //6.[各块间的间距]
        int ChartLeft = 80; //7.[图表左边距] ***图表距图的左边距离
        int ChartRight = 50; //8.[图表右边距] ***图表距图的右边距离
        int ChartTop = 50; //9.[图表顶边距] ***图表距图顶边距离
        int ChartBottom = 50; //10.[图表底边距] ***图表距图底边距离
        int YMaxValue = 100; //11.[纵坐标标尺最大值] ***纵坐标标尺的最大值
        int YItemNum = 10; //12.[纵坐标标尺段数] ***纵坐标标尺的段数
        int YTop = 15; //13.[距纵轴顶端间隔]
        int YStrStart = 35; //14.[纵坐标标尺文字起始X坐标]
        int XRight = 15; //15.[距横轴右端间隔]
        int XStrStart = 20; //16.[横坐标标尺文字起始Y坐标]
        //定义颜色
        Color[] cColor = { Color.Red, Color.Blue, Color.Green, Color.BlanchedAlmond, Color.Azure, Color.Gold, Color.Black, Color.Honeydew, Color.CadetBlue, Color.Yellow, Color.SpringGreen, Color.Teal, Color.Violet,Color.DimGray,Color.Firebrick,Color.ForestGreen,Color.HotPink,
                 Color.AliceBlue,Color.Azure,Color.BlanchedAlmond,Color.BlueViolet,Color.CadetBlue,Color.Coral,Color.Cornsilk,Color.DarkCyan,Color.DarkKhaki,Color.DarkOrange,Color.DarkSeaGreen,Color.DarkTurquoise,Color.DeepPink,Color.Fuchsia,Color.GhostWhite,Color.Gray};

        //[图表总宽度]=[总宽度]-[图表左边距]-[图表右边距]-[距横轴右端间隔]
        int chartwidth = ImgWidth - ChartLeft - ChartRight - XRight;
        //[项目宽度]=[图表总宽度]/[项目数量]
        int itemwidth = chartwidth / ItemNum;
        //[各块总占空间比率的实际宽度]=[项目宽度]*[各块总占空间比率]
        int factwidth = Convert.ToInt32(Math.Floor(itemwidth * ChildRate));
        //[各块矩形宽度]=[各块总占空间比率的实际宽度]/[块数]
        int rectanglewidth = factwidth / ChildNum;
        //[各块间的间距]=([项目宽度]-[各块总占空间比率的实际宽度])/([块数]+1)
        int childspace = Convert.ToInt32(Math.Floor((Double)((itemwidth - factwidth) / (ChildNum + 1))));

        Graphics objGps;//建立画板对象
        Bitmap objBitMap = new Bitmap(ImgWidth, ImgHeight);//建立位图对象
        objGps = Graphics.FromImage(objBitMap);//根据位图对象建立画板对象
        objGps.Clear(Color.White);//设置画板对象的背景色
     
       
      
        float[] arrValues ={ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };//比例
        float[] arrPrice ={ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };//价格
        float[] arrYItemNum ={ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };//Y轴刻度
        string[] arrValueNames ={ "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", };//城市
        string strGoodsid = "";
        
       
        for (int cod = 0; cod < ChildNum; cod++)
        {
            strGoodsid += ",Convert(numeric(20,2)," + strArea.Split(',')[cod].Split('|')[0].ToString()+")";
            arrValueNames[cod] = strArea.Split(',')[cod].Split('|')[1].ToString();
        }
        if (Type == "3")
        {
            strArea = arrValueNames[0];//记录地区
        }
        if (strGoodsid.Length > 0)
        {
            strGoodsid = strGoodsid.Remove(0, 1);
        }
        int ii = 0;
        double MaxPrice = 0.0, MinPrice = 0.0;
        //数据库连接
        Db db = new Db();
        string strSql = "";
        if (Type == "3")//十年比较
        {
            strSql = "Select " + strGoodsid + ",year From AreaPrice where goodsid=" + strId + " group by year,"+strGoodsid;
        }
        else
        {
            strSql = "Select " + strGoodsid + " From AreaPrice where goodsid=" + strId + " and year=" + strYear;
        }
        DataTable da = new DataTable();
        da = db.DataTable(strSql);
        if (Type == "3") //十年比较
        {
            for (int co = 0; co < da.Rows.Count; co++)
            {
                if (da.Rows[co][0].ToString() == "")
                {
                    arrPrice[ii] = 0;
                    MaxPrice = MaxPrice < 0 ? 0 : MaxPrice;
                    MinPrice = MinPrice > 0 ? 0 : MinPrice;
                }
                else
                {
                    arrPrice[ii] = (float)Convert.ToDouble((da.Rows[co][0]));
                    MaxPrice = MaxPrice < Convert.ToDouble(da.Rows[co][0]) ? Convert.ToDouble(da.Rows[co][0]) : MaxPrice;
                    MinPrice = MinPrice > Convert.ToDouble(da.Rows[co][0]) ? Convert.ToDouble(da.Rows[co][0]) : MinPrice;
                }

                //查找价格最大值，和最小值；
                arrValueNames[co] = da.Rows[co][1].ToString();
                ii++;
            }
        }
        else
        {
            for (int co = 0; co < da.Columns.Count; co++)
            {
                if (da.Rows[0][co].ToString() == "")
                {
                    arrPrice[ii] = 0;
                    MaxPrice = MaxPrice < 0 ? 0 : MaxPrice;
                    MinPrice = MinPrice > 0 ? 0 : MinPrice;
                }
                else
                {
                    arrPrice[ii] = (float)Convert.ToDouble(da.Rows[0][co]);
                    MaxPrice = MaxPrice < Convert.ToDouble(da.Rows[0][co]) ? Convert.ToDouble(da.Rows[0][co]) : MaxPrice;
                    MinPrice = MinPrice > Convert.ToDouble(da.Rows[0][co]) ? Convert.ToDouble(da.Rows[0][co]) : MinPrice;
                }

                //查找价格最大值，和最小值；

                ii++;
            }
        }
        db.Close();
        YMaxValue = Convert.ToInt32(MaxPrice + 1);//Y轴最大值
        //计算刻度
        for (int jj = 0; jj < YItemNum; jj++)
        {
            arrYItemNum[jj] = (YMaxValue / 10) * (jj + 1); //处理显示数据，进行图表数值对应 
        }
        // //[各块矩形宽度]=（[各块总占空间比率的实际宽度]-[各块间的间距]*（[块数]））/[块数]
        for (int jj = 0; jj < ii; jj++)
        {
            arrValues[jj] = (float)Math.Floor((Double)(ImgHeight - ChartBottom - ChartTop - YTop) * (arrPrice[jj] / YMaxValue)); //处理显示数据，进行图表数值对应 
        }
        //得出矩形宽度，和画图X轴位置
        //[项目宽度]=[总宽度]/[项目数量]
        //======[各块总占空间比率]=（[各块矩形宽度]+[各块间的间距]）/[项目宽度]
        //[各块总占空间比率的实际宽度]=[项目宽度]*[各块总占空间比率]
        //[一边空余空间宽度]=（[项目宽度]-[各块所占空间比率的总宽度]）/2 

        System.Drawing.Point[] pi = new Point[arrValues.Length]; //定义折线点的对象数组
        System.Drawing.Point[] pit = new Point[3]; //定义坐标三角点的对象数组
        System.Drawing.Pen pe = new Pen(new SolidBrush(cColor[6]), 1f); //定义画直线的对象
        //画纵轴
        objGps.DrawLine(pe, new Point(ChartLeft, ImgHeight - ChartBottom), new Point(ChartLeft, ChartTop));
        //画纵轴终点箭头
        pit[0].X = ImgWidth - ChartRight; //确定三角形三点的位置
        pit[0].Y = ImgHeight - ChartBottom - 4;
        pit[1].X = ImgWidth - ChartRight;
        pit[1].Y = ImgHeight - ChartBottom + 4;
        pit[2].X = ImgWidth - ChartRight + 10;
        pit[2].Y = ImgHeight - ChartBottom;
        objGps.FillPolygon(new SolidBrush(cColor[7]), pit);
    //画纵轴标尺和标尺描述
        for (int i = 1; i <= YItemNum; i++)
        {
            //画标尺
            objGps.DrawLine(pe, new PointF(ChartLeft, ImgHeight - ChartBottom - (ImgHeight - ChartBottom - ChartTop - YTop) / YItemNum * i), new PointF(ChartLeft - 5, ImgHeight - ChartBottom - (ImgHeight - ChartBottom - ChartTop - YTop) / YItemNum * i));
            //画描述
            objGps.DrawString(arrYItemNum[i - 1].ToString(), new Font("宋体", 10), Brushes.Black, new Point(YStrStart, ImgHeight - ChartBottom - (ImgHeight - ChartBottom - ChartTop - YTop) / YItemNum * i - 5));
        }
        //画横轴
        objGps.DrawLine(pe, new Point(ChartLeft, ImgHeight - ChartBottom), new Point(ImgWidth - ChartRight, ImgHeight - ChartBottom));
        //画横轴终点箭头
        pit[0].X = ChartLeft - 4; //确定三角形三点的位置
        pit[0].Y = ChartTop;
        pit[1].X = ChartLeft + 4;
        pit[1].Y = ChartTop;
        pit[2].X = ChartLeft;
        pit[2].Y = ChartTop - 10;
        objGps.FillPolygon(new SolidBrush(cColor[7]), pit);
        ////画横轴标尺和标尺描述
        //for (int i = 1; i <= ItemNum; i++)
        //{
        //    objGps.DrawLine(pe, new PointF(ChartLeft + itemwidth * i, ImgHeight - ChartBottom), new PointF(ChartLeft + itemwidth * i, ImgHeight - ChartBottom + 5));
        //    objGps.DrawString(arrValueNames[i - 1].ToString(), new Font("宋体", 10), Brushes.Black, new Point(ChartLeft + childspace + itemwidth * (i - 1), ImgHeight - ChartBottom + XStrStart));
        //}

        for (int j = 0; j < ii; j++)//画矩形图和折线图
        {
            if (Type == "1")
            {
                objGps.FillRectangle(new SolidBrush(cColor[j]), (j * (childspace + rectanglewidth)) + childspace + ChartLeft, ImgHeight - ChartBottom - arrValues[j], rectanglewidth, arrValues[j]);
                objGps.DrawRectangle(Pens.Black, (j * (childspace + rectanglewidth)) + childspace + ChartLeft, ImgHeight - ChartBottom - arrValues[j], rectanglewidth, arrValues[j]);
            }
            pi[j].X = (j * (childspace + rectanglewidth)) + childspace + ChartLeft;
            pi[j].Y = ImgHeight - ChartBottom - (int)arrValues[j];
            pe.SetLineCap(System.Drawing.Drawing2D.LineCap.RoundAnchor, System.Drawing.Drawing2D.LineCap.RoundAnchor, System.Drawing.Drawing2D.DashCap.Round);
            objGps.DrawString(arrPrice[j].ToString(), new Font("宋体", 10), Brushes.Black, pi[j].X, pi[j].Y - 15);//显示价格
            if (Type == "3")
            {
                objGps.DrawString(arrValueNames[j].ToString()+"年", new Font("宋体", 10), Brushes.Black, pi[j].X, ImgHeight - ChartBottom);//显示年
            }
            else
            {
                objGps.DrawString(arrValueNames[j].ToString(), new Font("宋体", 10), Brushes.Black, pi[j].X, ImgHeight - ChartBottom);//显示城市   
            }

            if ((j > 0) && (Type=="2"))
            {
                objGps.DrawLine(pe, pi[j - 1], pi[j]); //画折线
            }
            if ((j > 0) && (Type == "3"))
            {
                objGps.DrawLine(pe, pi[j - 1], pi[j]); //画折线
            }
        }
        if (Type == "3")
        {
             
            db = new Db();
            string strSqlName = "select distinct(areaprice.goodsid),ProductName  from SalerProduct,areaprice where areaprice.goodsid=salerproduct.goodsid and areaprice.goodsid=" + strId;
            da.Clear();
            da = db.DataTable(strSqlName);
            db.Close();
            objGps.DrawString(da.Rows[0].ItemArray[1].ToString() + "在" + strArea + "近几年价格", new Font("宋体", 10), Brushes.Blue, ImgWidth / 2 - (da.Rows[0].ItemArray[1].ToString().Length/2)*2, ImgHeight - 20);//显示城市
        }
       // objBitMap.Save(Response.OutputStream,ImageFormat.gif);//该位图对象以"GIF"格式输出
        objBitMap.Save(Server.MapPath("..\\Images\\") + strId + ".Gif", ImageFormat.Gif); //保存 Bmp图片。
        Image1.ImageUrl = "../Images/" + strId + ".Gif";
        //objBitMap.Save("d:\\" + strId + ".bmp", ImageFormat.Bmp); //保存 Bmp图片。

       //排序显示；  
        if (Type != "3")
        {

            string strSqlShwo = "@delete from AreaPriceCount";
            for (int i = 0; i < ChildNum; i++)
            {
                strSqlShwo += "@insert into AreaPriceCount select goodsid,year,'" + strArea.Split(',')[i].Split('|')[1].ToString() + "'," + strArea.Split(',')[i].Split('|')[0].ToString() + " from AreaPrice where [Year] =" + strYear + " and goodsid=" + strId;
            }
            db = new Db();
            db.ExecuteTransaction(strSqlShwo.Substring(1).Split(new char[] { '@' }), 30);
            da.Clear();
            da = db.DataTable("select ArearName as 地区,ArearPrice as 价格 from dbo.AreaPriceCount where goodsid=" + strId + " and year=" + strYear + " order by arearprice");
            db.Close();
            GridView1.DataSource = da;
            GridView1.DataBind();
        }
    }

    private void BindGrid()
    {
        Db db = new Db();
        GridView1.DataSource = db.DataTable("select ArearName as 地区,ArearPrice as 价格 from dbo.AreaPriceCount where goodsid=" + strId + " and year=" + strYear + " order by arearprice " + ViewState["sortdirection"]);
        GridView1.DataBind();
        db.Close();
    
    }
    /// <param name="red">自定义颜色红色分量值，有效值0到255</param>
    /// <param name="green">自定义颜色绿色分量值，有效值0到255</param>
    /// <param name="blue">自定义颜色蓝色分量值，有效值0到255</param>
    /// <returns></returns>
    public static Color GetColor(int red, int green, int blue)
    {
        Color objColor = new Color();
        objColor = Color.FromArgb(red, green, blue);
        return objColor;
    }


    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {    
        if (ViewState["sortdirection"] == null)
        {
            ViewState["sortdirection"] = "asc";
        }
        else
        {
            if (ViewState["sortdirection"].ToString() == "asc")
            {
                ViewState["sortdirection"] = "desc";
            }
            else
            {
                ViewState["sortdirection"] = "asc";
            }
        }
        BindGrid();


    }
}
